package edu.bbk.muc.lifetracker.sensormanager;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import edu.bbk.muc.lifetracker.common.Configuration;
import edu.bbk.muc.lifetracker.common.SensorsToUi;
import edu.bbk.muc.lifetracker.common.UiToSensors;

/**
 * Interface for classes that coordintate sensor's recording and logging.
 * 
 * @author irenatyler and romankirillov
 * 
 */
public class SensorManager implements UiToSensors {
  private Configuration configuration;

  private final SensorsToUi sensorsToUi;
  private final Activity callingActivity;
  private final List<Recorder> sensors = new ArrayList<Recorder>();

  public SensorManager(
      Configuration initialConfiguration,
      SensorsToUi sensorsToUi,
      Activity callingActivity,
      AbstractSensorFactory factory) {
    // initializing fields
    this.configuration = initialConfiguration;
    this.sensorsToUi = sensorsToUi;
    this.callingActivity = callingActivity;

    // creating sensors
    sensors.addAll(factory.createSensors(this.callingActivity, this.sensorsToUi));
    onConfigurationChanged(this.configuration);
  }

  @Override
  public boolean onConfigurationChanged(Configuration configuration) {
    this.configuration = configuration;
    if (configuration.isLoggingEnabled() == false) {
      onStop();
    } else {
      for (Recorder sensor : sensors) {
        sensor.acceptNewConfiguration(this.configuration);
      }
    }
    return true;
  }

  @Override
  public void onPause() {
    onStop();
  }

  @Override
  public void onResume() {
    onStart();
  }

  @Override
  public void onStart() {
    for (Recorder sensor : sensors) {
      sensor.doStart();
    }
  }

  @Override
  public void onStop() {
    for (Recorder sensor : sensors) {
      sensor.doStop();
    }
  }
}
